using System;
using System.Linq;
using System.Web.Mvc;
using Mvc.Validation;
using web_uchet.Models;
using web_uchet.JQgridProcess;
using web_uchet.ViewModels;

namespace web_uchet.Controllers
{   
    public class ViewOrderController : MasterPageController
    {
        private ViewЗаказOperationProvider _Provider;
        public ViewOrderController()
        {
            this._Provider = new ViewЗаказOperationProvider(this._MasterData);  
            
        }
        public ViewOrderController(ViewЗаказOperationProvider Provider)
        {
            this._Provider = Provider;
        }
        //
        // GET: /ViewWorkPlace/
        //[Authorize(Roles = "Администратор,Просмотр")]
        //public ActionResult Index()
        //{
        //    //if (this.Request.IsAjaxRequest()) 
        //        return this.IndexForJQGrid(new GridSettings());
        //    //else
        //    //    return View(
        //    //        this._Provider.List(
        //    //        this._MasterData.CompanyID)
        //    //        );            
        //}
        //
        [Authorize(Roles = "Администратор,Менеджер,Просмотр")]
        public ActionResult Index(GridSettings grid)//(string sidx, string sord, int? page, int? rows)
        {
            if (this.Request.IsAjaxRequest())
            {
                var query = this._Provider.IQueryableOrders(this._MasterData.CompanyID, new int?(),new int?());

                var data = query.GetGridFilteredData(grid);

                //converting in grid format
                object result = ViewЗаказOperationProvider.getJSONForJQGrid(data, grid);

                //convert to JSON and return to client
                return Json(result,JsonRequestBehavior.AllowGet);

            }
            else return View();
        }
        [Authorize()]
        public ActionResult MyOrders(GridSettings grid, int? id)
        {
            if (this.Request.IsAjaxRequest())
            {
                var query = this._Provider.IQueryableOrders(new int?(), id, new int?());

                var data = query.GetGridFilteredData(grid);

                //converting in grid format
                object result = ViewЗаказOperationProvider.getJSONForJQGrid(data, grid);

                //convert to JSON and return to client
                return Json(result,JsonRequestBehavior.AllowGet);

            }
            else return View();
        }

        [Authorize(Roles = "Администратор,Менеджер,Просмотр")]
        public ActionResult ClientOrders(GridSettings grid, int? id)
        {
            if (this.Request.IsAjaxRequest())
            {
                var query = this._Provider.IQueryableOrders(this._MasterData.CompanyID, new int?(), id);

                var data = query.GetGridFilteredData(grid);

                //converting in grid format
                object result = ViewЗаказOperationProvider.getJSONForJQGrid(data, grid);

                //convert to JSON and return to client
                return Json(result, JsonRequestBehavior.AllowGet);
            }
                return View();
        }

        [Authorize(Roles = "Администратор,Менеджер,Просмотр")]
        public ActionResult Today(GridSettings grid, DateTime? date)
        {
            if (this.Request.IsAjaxRequest())
            {
                var query = this._Provider.IQueryableOrders(this._MasterData.CompanyID, new int?(), new int?());
                if (date.HasValue)
                    query = this._Provider.FilterByDate(query, date.Value);

                var data = query.GetGridFilteredData(grid);

                //converting in grid format
                object result = ViewЗаказOperationProvider.getJSONForJQGrid(data, grid);

                //convert to JSON and return to client
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            return View();
        }

        [Authorize(Roles = "Администратор,Менеджер,Просмотр")]
        public ActionResult Tomorrow(GridSettings grid, DateTime? date)
        {
            if (this.Request.IsAjaxRequest())
            {
                var query = this._Provider.IQueryableOrders(this._MasterData.CompanyID, new int?(), new int?());
                if (date.HasValue)
                    query = this._Provider.FilterByDate(query, date.Value);

                var data = query.GetGridFilteredData(grid);

                //converting in grid format
                object result = ViewЗаказOperationProvider.getJSONForJQGrid(data, grid);

                //convert to JSON and return to client
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            return View();
        }
        
        [Authorize(Roles = "Администратор,Менеджер,Просмотр")]
        public ActionResult DateRange(GridSettings grid, DateTime? DateStart,DateTime? DateEnd)
        {
            if (this.Request.IsAjaxRequest())
            {
                var query = this._Provider.IQueryableOrders(this._MasterData.CompanyID, new int?(), new int?());
                if (DateStart.HasValue && !DateEnd.HasValue)
                    query = this._Provider.FilterByDate(query, DateStart.Value);
                else if (DateStart.HasValue && DateEnd.HasValue) 
                    query = this._Provider.FilterByDateRange(query, DateStart.Value, DateEnd.Value);

                var data = query.GetGridFilteredData(grid);

                //converting in grid format
                object result = ViewЗаказOperationProvider.getJSONForJQGrid(data, grid);

                //convert to JSON and return to client
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            return View();
        }

        //
        // GET: /ViewWorkPlace/Details/5
        [Authorize(Roles = "Администратор,Менеджер,Просмотр,Исполнитель")]
        public ActionResult Details(Int64 id)
        {
            if (this.Request.IsAjaxRequest())
            {
                return PartialView("DetailsPartial", this._Provider.Details(id,true));
            }
            else
                return View(this._Provider.Details(id, true));
        }
        //
        // GET: /ViewWorkPlace/Create
        [Authorize(Roles = "Администратор,Менеджер")]
        public ActionResult Create()
        {
            ViewData.Add("IEnumCurrencies",this._Provider.GetIEnumCurrencies());
            ViewData.Add("IEnumServices", this._Provider.GetIEnumServices());
            ViewData.Add("CurrencyID", this._Provider.GetCurrencies(new int?()));
            ViewData.Add("ClientID", this._UserOperationProvider.GetUserCompanysClients(this._MasterData.CompanyID,new int?()));
            ViewData.Add("ExecutiveID", this._UserOperationProvider.GetCompanysExecutives(this._MasterData.CompanyID, new int?()));
            ViewData.Add("ManagerID", this._UserOperationProvider.GetCompanysManagers(this._MasterData.CompanyID, new int?()));
            ViewData.Add("IsAjaxRequest", this.Request.IsAjaxRequest());
            if (Request.IsAjaxRequest())
            {
                return PartialView("CreatePartial");
            }
            else
            return View(new ViewЗаказ());
        } 

        //
        // POST: /ViewWorkPlace/Create
        [Authorize(Roles = "Администратор,Менеджер")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(ViewЗаказ NewObject,bool WithDetail)
        {
            try
            {   
                NewObject.Validate();
                this._Provider.Create(NewObject);

                if (Request.IsAjaxRequest())
                {
                    if (WithDetail) return this.Edit(NewObject.ИД_Заказа);
                    else
                        return this.Content("Заказ создан", "text/html");
                }
                else
                {
                    if (WithDetail) return this.RedirectToAction("Edit", new { id = NewObject.ИД_Заказа });
                    else
                    return RedirectToAction("Index");
                }
                
            }
            catch (EntityValidationException ex)
            {
                ViewData.ModelState.PopulateWithErrors(ex);
                ViewData.Add("IEnumCurrencies", this._Provider.GetIEnumCurrencies());
                ViewData.Add("IEnumServices", this._Provider.GetIEnumServices());
                ViewData.Add("CurrencyID", this._Provider.GetCurrencies(new int?()));
                ViewData.Add("ClientID", this._UserOperationProvider.GetUserCompanysClients(this._MasterData.CompanyID, new int?()));
                ViewData.Add("ExecutiveID", this._UserOperationProvider.GetCompanysExecutives(this._MasterData.CompanyID, new int?()));
                ViewData.Add("ManagerID", this._UserOperationProvider.GetCompanysManagers(this._MasterData.CompanyID, new int?()));
                ViewData.Add("IsAjaxRequest", this.Request.IsAjaxRequest());
                if (Request.IsAjaxRequest())
                {
                    return PartialView("CreatePartial", NewObject);
                }
                else
                    return View(NewObject);
            }
        }
        //
        // GET: /ViewWorkPlace/Edit/5
        [Authorize(Roles = "Администратор,Менеджер")]
        public ActionResult Edit(Int64 id)
        {
            ViewЗаказ EditObject=this._Provider.Details(id,true);
            ViewData.Add("IEnumCurrencies", this._Provider.GetIEnumCurrencies());
            ViewData.Add("IEnumServices", this._Provider.GetIEnumServices());
            ViewData.Add("CurrencyID", this._Provider.GetCurrencies(new int?(EditObject.CurrencyID)));
            ViewData.Add("ClientID", this._UserOperationProvider.GetUserCompanysClients(this._MasterData.CompanyID, new int?(EditObject.ClientID)));
            ViewData.Add("ExecutiveID", this._UserOperationProvider.GetCompanysExecutives(this._MasterData.CompanyID, new int?(EditObject.ExecutiveID)));
            ViewData.Add("ManagerID", this._UserOperationProvider.GetCompanysManagers(this._MasterData.CompanyID, new int?(EditObject.ManagerID)));
            ViewData.Add("IsAjaxRequest", this.Request.IsAjaxRequest());
            if (this.Request.IsAjaxRequest())
            {
                return PartialView("EditPartial", EditObject);
            }
            else
                return View(EditObject);
        }
        //
        // POST: /ViewWorkPlace/Edit/5
        [Authorize(Roles = "Администратор,Менеджер")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Int64 id, FormCollection collection)
        {
            ViewЗаказ EditObject = this._Provider.Details(id,false);
            try
            {       
                UpdateModel<ViewЗаказ>(EditObject, collection.ToValueProvider());
                EditObject.Validate();
                this._Provider.LogOrderChanges(EditObject.Заказ);
                this._Provider.SaveChanges(EditObject);
                if (this.Request.IsAjaxRequest())
                {
                    return this.Content("Изменения сохранены", "text/html");
                }
                else
                return this.RedirectToAction("Details", new { id = id });
            }
            catch (EntityValidationException ex)
            {
                ViewData.ModelState.PopulateWithErrors(ex);
                ViewData.Add("IEnumCurrencies", this._Provider.GetIEnumCurrencies());
                ViewData.Add("IEnumServices", this._Provider.GetIEnumServices());
                ViewData.Add("CurrencyID", this._Provider.GetCurrencies(new int?(EditObject.CurrencyID)));
                ViewData.Add("ClientID", this._UserOperationProvider.GetUserCompanysClients(this._MasterData.CompanyID, new int?(EditObject.ClientID)));
                ViewData.Add("ExecutiveID", this._UserOperationProvider.GetCompanysExecutives(this._MasterData.CompanyID, new int?(EditObject.ExecutiveID)));
                ViewData.Add("ManagerID", this._UserOperationProvider.GetCompanysManagers(this._MasterData.CompanyID, new int?(EditObject.ManagerID)));
                ViewData.Add("IsAjaxRequest", this.Request.IsAjaxRequest());
                if (this.Request.IsAjaxRequest())
                {
                    return PartialView("EditPartial", EditObject);
                }
                else
                    return View(EditObject);
            }
        }
        [Authorize(Roles = "Администратор")]
        public ActionResult Delete(Int64 id)
        {           
            if (Request.IsAjaxRequest())
            {
                this._Provider.Delete(id);
                return this.Content("Заказ удален", "text/html");
            }
            else
            {
                this._Provider.Delete(id);
                return RedirectToAction("Index");
            }
        }
        [Authorize(Roles = "Администратор,Менеджер")]
        public ActionResult Cancel(Int64 id)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    this._Provider.Cancel(id, this._MasterData);
                    return this.Content("Заказ отменен", "text/html");
                }
                catch (Exception ex)
                {
                    return this.Content(ex.Message, "text/html");
                }
            }
            else
            {
                this._Provider.Cancel(id, this._MasterData);
                return this.RedirectToAction("Details", new {id=id});
            }
        }
        [Authorize(Roles = "Администратор,Менеджер,Исполнитель")]
        //[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SetExecuted(Int64 id, DateTime? ExecutedDate)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    this._Provider.SetExecuted(id, ExecutedDate);
                return this.Content("Заказ помечен выполненным", "text/html");
                }
                catch (Exception ex)
                {
                    return this.Content(ex.Message, "text/html");
                }
            }
            else
            {
                this._Provider.SetExecuted(id, ExecutedDate);
                return this.RedirectToAction("Details", new { id = id });
            }            
        }

        [Authorize(Roles = "Исполнитель")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult UnHostedOrders()
        {
            return View(this._Provider.GetUnHostedOrders());
        }

        [Authorize(Roles = "Исполнитель")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult HostOrder(Int64 id)
        {
            if (Request.IsAjaxRequest())
            {
                if (this._Provider.HostOrder(id))
                    return Content("Заказ назначен на Вас");
                else
                    return Content("Заказ не назначен на Вас, т.к. кто-то другой успел раньше Вас");
            }
            else return new EmptyResult();
        }
    }
}
